//
//  商品分类-Selector.swift
//  smosky
//
//  Created by zhu xietong on 2018/5/23.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import JoLoading
import AsyncDisplayKit

private let children_key = "children"
public class CateSelector: JoView,LoadingPresenter,TableVConfig,ASTableVConfig{
    public static var global:NSMutableArray? = nil
    
    public var sellerID:String? = nil
    
    public var cateURL:String? = nil
    
    public var confirm:([String:Any])->Void = {_ in}
    
    
    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        confirm(["name":"cate","value":["cate":model["id",""]],"raw":model])
    }
    
    public var loadingPresenterInset: UIEdgeInsets{
        get{
            return .zero
        }
    }
    public var LoadingClass:JoLoading.Type = SimpleLoading.self
    public let leftTb = UITableView(frame: .zero, style: .plain)
    public let rightNode = ASTableNode(style: .plain)
    public var rightTb:UITableView{
        get{
            return rightNode.view
        }
    }
    
    
    
    public var lsection:TP.section{
        get{
            let sec:TP.section = [
                [
                ]
            ]
            return sec
        }
    }
    public let lselector:TP.selector = [
        "<default>":Lever1Cell.self,
        ]
    
    var rsection:TP.section{
        get{
            let sec:TP.section = [
                [
                ]
            ]
            return sec
        }
    }
    let rselector:TP.selector = [
        "<default>":Lever2Cell.self,
    ]
    
    
    
    var datas = NSMutableArray(){
        didSet{
            self.leftItem = nil
            self.rightItem = nil
            
            
            datas.list { (dict:NSMutableDictionary, i) in
                dict[FK.selected] = FK.NO
            }
            if let _ = sellerID
            {
                if datas.count > 1
                {
                    if let one = datas[1] as? NSMutableDictionary{
                        one[FK.selected] = "YES"
                        self.leftItem = one
                    }
                }
            }
            else{
                if let one = datas.firstObject as? NSMutableDictionary{
                    one[FK.selected] = "YES"
                    self.leftItem = one
                }
            }
            leftTb.model["section0"] = datas
            leftTb.reloadData()
            
        }
    }
    var rightDatas = NSMutableArray(){
        didSet{
            rightTb.reloadData()
        }
    }
    
    func updateDatas() {
        
        if datas.count < 1
        {
            mo_request_send()
        }
    }
    
    override public func addLayoutRules() {
        
        
        let line = UIView()
        let line2 = UIView()
        
        let contenV = UIView()
        let w = 1.0/3.0 * Swidth
        contenV.eelay = [
            [leftTb,[ee.T.L.B,[0,0,0]],w],
            [line,[leftTb,ee.R,ee.L],0.5,[ee.T.B]],
            [rightTb,[line,ee.R,ee.L],[ee.T.R.B,[0,0,0]]],
            //            [line2,[ee.T.L.R],"0.4"]
        ]
        
        backgroundColor = ._background
        jo_contentView.backgroundColor = ._background
        
        jo_contentView.eelay = [
            [contenV,[ee.T.L.B.R]]
        ]
        
        leftTb.backgroundView?.backgroundColor = .clear
        leftTb.backgroundColor = .clear
        rightTb.backgroundView?.backgroundColor = .clear
        rightTb.backgroundColor = .clear
        
        
        
        leftTb.showsVerticalScrollIndicator = false
        line.backgroundColor = ._separator
        line2.backgroundColor = ._separator
        
        
        self.configTables(tables: leftTb)
        self.configTables(nodes: rightNode)
        leftTb.buildDynamicHeight()
        
//        leftTb.backgroundColor = UIColor(shex: "#E1DFDF")
        leftTb.separatorStyle = .none
        
        leftTb.load(sections: lsection, selector: lselector)
        rightNode.load(sections: rsection, selector: rselector)
        
        
//        rightTb.backgroundColor = UIColor(shex: "#f4f4f4")
        rightTb.alwaysBounceVertical = true
        rightTb.separatorStyle = .none
        
        
    }
    
    
    var leftItem:NSMutableDictionary? = nil{
        didSet(oldValue){
            guard let new = leftItem else{return}
            oldValue?[FK.selected] = "NO"
            
            new[FK.selected] = "YES"
            if let section0 = new["section0"] as? NSMutableArray
            {
                rightNode.model <-- ("section0",section0,NodeInsert.arrayRefresh)
                rightNode.reloadData()
                return
            }
            
            let section0 = NSMutableArray()
            
            var currentOptions = NSMutableArray()
            let list1 = DataNode.path(node: children_key, new, value: NSMutableArray())
            list1.list { (dict:NSMutableDictionary, i) in
                let list2 = DataNode.path(node: children_key, dict, value: NSMutableArray())
                if list2.count > 0
                {
                    
                    if currentOptions.count > 0
                    {
                        let oldItem = NSMutableDictionary()
                        oldItem[FK.options] = currentOptions
                        section0.add(oldItem)
                    }
                    
                    let item = NSMutableDictionary()
                    currentOptions = NSMutableArray()
                    
                    let one = dict.mutable_dictionary
                    one[children_key] = ""
                    currentOptions.add(one)
                    dict[FK.selected] = FK.NO
                    
                    one["cellID"] = "lever2"
                    list2.list({ (obj:NSMutableDictionary, i) in
                        let son = obj.mutable_dictionary
                        son[children_key] = ""
                        currentOptions.add(son)
                    })
                    
                    item[FK.options] = currentOptions
                    section0.add(item)
                    currentOptions = NSMutableArray()
                }
                else{
                    let one = dict.mutable_dictionary
                    one[children_key] = ""
                    currentOptions.add(one)
                    dict[FK.selected] = FK.NO
                }
            }
            
            if currentOptions.count > 0
            {
                let oldItem = NSMutableDictionary()
                oldItem[FK.options] = currentOptions
                section0.add(oldItem)
            }
            new["section0"] = section0
            rightNode.model <-- ("section0",section0,NodeInsert.arrayRefresh)
            rightNode.reloadData()
        }
        
    }
    

    
    var rightItem:NSMutableDictionary? = nil
    {
        didSet{
            
        }
    }
    
    //只有一级分类的处理成二级分类
    func checkAndAppendSecondLeverData(list:NSMutableArray) {
        list.list { (dict:NSMutableDictionary, i) in
            let list2 = DataNode.path(node: children_key, dict, value: NSMutableArray())
            if list2.count < 1{
                list2.add(dict.mutable_dictionary)
            }
        }
    }
    
    
    func mo_request_send() {
        
        weak var wself = self        
        if let ID = sellerID
        {
            loadingV.loading(message: "", title: "")
            JoTask().params(["merchid":ID]).post._surl(.商品分类).json_handle { (status, msg, obj, resp) in
                wself?.loadingV.dismiss()
                if status.isSuccess{
                    if let list = DataNode<NSMutableArray>.path(node: "category", obj)
                    {
                        wself?.checkAndAppendSecondLeverData(list: list)
                        list.insert(["name":"全部".loc,"id":""].mutable_dictionary, at: 0)
                        wself?.datas = list
                        return
                    }
                    wself?.loadingV.show(message: msg, title: "")
                }
                }.run()
            return
        }
        if let url = cateURL
        {
            loadingV.loading(message: "", title: "")
            JoTask().log.post.url(url).json_handle { (status, msg, obj, resp) in
                wself?.loadingV.dismiss()
                if status.isSuccess{
                    if let list = DataNode<NSMutableArray>.path(node: "category", obj)
                    {

                        wself?.checkAndAppendSecondLeverData(list: list)
                        list.insert(["name":"全部".loc,"id":""].mutable_dictionary, at: 0)
                        wself?.datas = list
                        return
                    }
                    wself?.loadingV.show(message: msg, title: "")
                }
                }.run()
            return
        }
        
        if let cate = CateSelector.global{
            self.datas = cate
            return
        }
        loadingV.loading(message: "", title: "")
        
        JoTask().post._surl(.商品分类).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let list = DataNode<NSMutableArray>.path(node: "category", obj)
                {
                    wself?.datas = list
                    list.insert(["name":"全部".loc,"id":""].mutable_dictionary, at: 0)
                    wself?.checkAndAppendSecondLeverData(list: list)
                    CateSelector.global = list
                    return
                }
                wself?.loadingV.show(message: msg, title: "")
            }
            //            let list = [
            //                [
            //                    "name":"服装","children":
            //                        [
            //                            [
            //                                "name":"女装","icon":__images.one_str,
            //                                "children":[
            //                                    ["name":"女装1","icon":__images.one_str],
            //                                    ["name":"女装2","icon":__images.one_str],
            //                                    ["name":"女装3","icon":__images.one_str],
            //                                    ["name":"女装4","icon":__images.one_str],
            //                                    ["name":"女装5","icon":__images.one_str],
            //                                ],
            //                            ],
            //                            ["name":"男装","icon":__goods.one_str],
            //                            ["name":"上衣","icon":__goods.one_str],
            //                            ["name":"外套","icon":__goods.one_str],
            //                            ["name":"鞋子","icon":__goods.one_str],
            //                            ["name":"时尚","icon":__goods.one_str],
            //                    ],
            //                    ],
            //                [
            //                    "name":"数码","children":
            //                        [
            //                            ["name":"手机","icon":__goods.one_str],
            //                            ["name":"平板","icon":__goods.one_str],
            //                            ["name":"PC","icon":__goods.one_str],
            //                            ["name":"苹果","icon":__goods.one_str],
            //                            ["name":"安卓","icon":__goods.one_str],
            //                    ],
            //                    ],
            //                [
            //                    "name":"家电","children":
            //                        [
            //                            ["name":"洗衣机","icon":__goods.one_str],
            //                            ["name":"油烟机","icon":__goods.one_str],
            //                            [
            //                                "name":"冰箱","icon":__goods.one_str,
            //                                "children":[
            //                                    ["name":"冰箱1","icon":__goods.one_str],
            //                                    ["name":"冰箱2","icon":__goods.one_str],
            //                                    ["name":"冰箱3","icon":__goods.one_str],
            //                                    ["name":"冰箱4","icon":__goods.one_str],
            //                                    ["name":"冰箱5","icon":__goods.one_str],
            //                                ],
            //
            //                            ],
            //
            //                    ]
            //                ]
            //                ].mutable_array
            //            wself?.datas = list.mutable_array
            //                    return
            //                }
            //            }
            //            wself?.mo_request_alert(msg:msg, title: "", bt_title: "重拾")
            }.run()
    }
    
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let data = tableView.cellData(at: indexPath) else {
            return
        }
        
        if data["id",""] == ""//全部
        {
            confirm(["name":"cate","value":["cate":""]])
            return
        }
        
        leftItem = data
        tableView.reloadData()
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let data = collectionView.cellData(at: indexPath) else {
            return
        }
        rightItem = data
        //        confirm(values: obj)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return [16,16,16,16]
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let item = rightDatas[indexPath.row] as? NSMutableDictionary
        {
            if item["cellID",""] == "lever2"
            {
                let w = (2.0/3.0) * Swidth - 32
                return CGSize(width: w, height: 36)
            }
        }
        let w = (2.0/3.0) * Swidth
        let size = w/3.0
        return CGSize(width: size, height: size+30)
    }
    
}


public class GoodsCateSelector:FilterDropSelector
{
   public let selector:CateSelector = CateSelector()
    
    override public var contentHeight: CGFloat{
        return (Sheight-TP.topHeight-38)
    }
    
    override public func addLayoutRules() {
        
        backgroundColor = ._background
        contentView.backgroundColor = ._background
        
        contentView.eelay = [
            [selector,[ee.T.L.B.R]]
        ]
        
        selector.confirm = {[weak self] (info)in
            self?.confirm(values: info)
        }
        
    }
    
    override public func didShow() {
        selector.updateDatas()
    }
}

public class GoodsSellerCateSelector:FilterOptionsSelectorController
{
    
    public var sellerID:String? = nil
    {
        didSet{
            selector?.sellerID = sellerID
        }
    }
    public var cateURL:String? = nil
    {
        didSet{
            selector?.cateURL = cateURL
        }
    }
    
    
    public var didSelectItem:([String:Any]) ->Void = {_ in}
    
    public var selector:CateSelector? = nil
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "商品分类"
        let selector:CateSelector = CateSelector()
        selector.sellerID = self.sellerID
        
        view.eelay = [
            [selector,[ee.L.B.R],[ee.T,TP.topHeight]],
        ]
        view.backgroundColor = .clear
        selector.confirm = {[weak self]
            info in
            
            self?.confirm(values: info)
            self?.didSelectItem(info)
            self?.navigationController?.popViewController(animated: true)
        }
        self.selector = selector
        
        if #available(iOS 11.0, *) {
            selector.leftTb.contentInsetAdjustmentBehavior = .never
            selector.rightTb.contentInsetAdjustmentBehavior = .never
            
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
    }
    
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        selector?.sellerID = sellerID
        selector?.cateURL = cateURL
        
        selector?.updateDatas()
    }
}

extension CateSelector{
    
    class Header: JoView {
        let titleL = UILabel()
        override func addLayoutRules() {
            eelay = [
                [titleL,[ee.L.R,[AppTheme.edge,-AppTheme.edge]],[ee.T.B,[10,-10]]],
            ]
            titleL.ui.font12.text(color: ._foreground)
        }
    }
    
    class BaseCell: JoCheckedCell {
        
    }
    class Lever1Cell: BaseCell {
        let nameL = UILabel()
        let indicatorV = UIView()
        override func addLayoutRules() {
            contentView.eelay = [
                [nameL,[ee.T.B,[15,-15]],[ee.L.R,[10,-10]],"20"],
            ]
            _ = nameL.ui.font14.center.text(color: ._foreground)
            self.selectionStyle = .none
        }
        
        override func updateIsChecked() {
            if mo.model[FK.selected,""] == "YES"
            {
                contentView.backgroundColor = UIColor._background.maskColor
            }
            else{
                contentView.backgroundColor = UIColor._background
            }
        }
        
        override func mo_model_reload() {
            nameL.text = mo.model.possible("name", default: "XX")
            self.isChecked = mo.model[FK.selected,FK.NO] == FK.YES
        }
    }
    
    class Lever3Cell: JoCollectionCell {
        let nameL = UILabel()
        let imgV = UIImageView()
        override func addLayoutRules() {
            
            contentView.eelay = [
                [imgV,[ee.T.L.R,[5,0,0]],[ee.B,-40]],
                [nameL,[ee.L.R],"17",[imgV,ee.B,ee.T,6]],
            ]
            
            _ = nameL.ui.font12.center.text(color: .color(light: "#666", dark: "#aaa"))
            imgV.ui.holder(type: .grayBack)
            imgV.backgroundColor = .clear
            //            self.selectionStyle = .default
        }
        
        override func mo_model_reload() {
            nameL.text =  mo.model.possible("name", default: "XX")
            imgV.img_url = mo.model["thumb",""]
        }
    }
    
    class Lever2Cell: JoCellNode,EeActionDelegate{
        func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
            active(ID: "confirmCate", object: data)
        }
        
        class Kit: JoTouchNode {
            let imgV = JoImageNode()
            let titleL = JoTextNode()
            override func addLayoutRules() {
                imgV.ui.holder(type: .grayBack)

            }
            
            override func mo_model_reload() {

                imgV.ui.holder(type: .grayBack)
                
                imgV.img_url = mo.model["thumb",""]

                //                "ss".ui.bfont11
                titleL.textNode.maximumNumberOfLines = 1
                titleL.attributedText =  mo.model.possible("name", default: "XX").ui.color(color: .color(light: "#444", dark: "#ccc")).font12.astring
                
            }
            override func specGetter() -> _Spec {
                let w :CGFloat = Swidth*(2.0/3.0) - 40
                if mo.model["cellID",""] == "lever2"
                {
                    return .inset([], [0,10,14,10], child: titleL["16",w])
                }
                else{
                    let kit_w:CGFloat = w/3.0 - TP.separatorHeight
                    let kit_h:CGFloat = w/3.0 - TP.separatorHeight  + 24
                    
                    let img_w = kit_w - 10
                    
                    return .stack([kit_w,"\(kit_h)",&-.center,"v|6"], childs: [imgV["\(img_w)",img_w],titleL.Spec])
                    
                }
            }
        }
        
        let list = JoRuleNode<Kit>()
        let back = ASDisplayNode()
        
//        override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
//
//        }
        override func mo_model_reload() {
            list.containerConfig = {
                spec in
                spec.justifyContent = .start
            }
            list.space = 0
            list.nodePath = FK.options
            list.mo.model = mo.model
            list.delegate = self
            //            list.backgroundColor = .white
            back.view.backgroundColor = ._background
        }
        override func specGetter() -> _Spec {
            let content:_Spec = .inset([], [30,20,10,20], child: list.Spec)
            
            return .back([], over: content, back: .inset([], [10,10,0,10], child: back.Spec))
            //            return .over([], over: content, back: .inset([], [-10], child: back.Spec))
        }
        
    }
    
}

